package com.hjk.waibao.mj.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpUtil;
import com.hjk.waibao.mj.annotation.PostPara;
import com.hjk.waibao.mj.bean.ApiResult;
import com.hjk.waibao.mj.common.model.Image;
import com.jfinal.core.Controller;
import com.jfinal.json.Json;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

/**
 * @Description
 * @Author hjk
 * @Date 2020/4/15
 **/
public class ImageController extends Controller {
    public void index() throws IOException {
        String id = getPara("id");
        Image image = Image.dao.findById(id);
        if (image != null) {
            getResponse().setContentType(image.getType());
            getResponse().getOutputStream().write(image.getValue());
        } else {
            String imagePath = PropKit.get("imagePath");
            getResponse().setContentType(id.endsWith("jpg") ? "image/jpeg" : (id.endsWith("gif") ? "image/gif" : "image/png"));
            getResponse().getOutputStream().write(FileUtil.readBytes(new File(new File(imagePath), id)));
        }
        renderNull();
    }


    public void submitImageByUrl(@PostPara String imageUrlStr) throws MalformedURLException {
        String[] imageUrlArray = imageUrlStr.split("\n");
        ArrayList<Image> resultList = new ArrayList<>();
        for (Object o : imageUrlArray) {
            Image image = new Image();
            String urlStr = o.toString();
            image.setType(urlStr.contains("jpg") ? "image/jpeg" : (urlStr.contains("gif") ? "image/gif" : "image/png"));
            byte[] bytes = HttpUtil.createGet(urlStr).execute().bodyBytes();
            String s = MD5.create().digestHex(bytes);
            image.setId(s);
            image.setName(StrUtil.toString(urlStr).length() > 255 ? urlStr.substring(0, 254) : urlStr);
            image.setValue(bytes);
            try {
                image.save();
            } catch (Exception e) {
                if (e.getMessage().contains("Duplicate entry"))
                    image.update();
            }
            resultList.add(image);
        }
        renderJson(ApiResult.createSuccess(resultList));
    }

    public void list(@PostPara Integer pageNumber, @PostPara Integer pageSize) {
        Page<Record> page = Db.paginate(pageNumber, pageSize,
                "select id,`name`", " from t_image order by id desc");
        renderJson(ApiResult.createSuccessWithJsonDataJson("", Json.getJson().toJson(page)));
    }

    public void listImageFromUrl(@PostPara Integer pageNumber, @PostPara Integer pageSize) {
        Page<Record> page = Db.paginate(pageNumber, pageSize,
                "select *", " from t_image_from_url order by id desc");
        renderJson(ApiResult.createSuccessWithJsonDataJson("", Json.getJson().toJson(page)));
    }

    public void captcha() {
        renderCaptcha();
    }

    public void up() {
        render("up.html");
    }

    public void upload() {
        UploadFile uploadFile = getFile("file");
        try {
            byte[] fileBytes = FileUtil.readBytes(uploadFile.getFile());
            String id = Image.saveImage(fileBytes, uploadFile.getContentType(), uploadFile.getFileName());
            renderText(id);
        } finally {
            uploadFile.getFile().delete();
        }
    }
}
